const fs = require('fs-extra');
const compressing = require('compressing');
const packages = fs.readJSONSync('./exposes/config.json');
const path = require('path')

const targetFolder = './desk/extensions/portal';
const fromFolder = './dist';


/*
 *生成语言包文件
 */

 const genLangJson = () => {
  const widgetsInfo = Object.values(packages.exposes).map(data => data);
  widgetsInfo.forEach(widget => {
    const widgetName = widget.name;
    const widgetI18nFile = path.resolve(widget.import, '../languages');
    fs.readdirSync(widgetI18nFile).forEach((lang) => {
      const langUrl = path.resolve(widget.import, `../languages/${lang}`);
      const jsonData = parseLanguageFile(langUrl);
      const langName = lang.replace(/\.ts|\.js/, '');
      if (jsonData) {
        createDirectoryIfNotExist(targetFolder, [widgetName, 'lang']);
        fs.writeJSONSync(`${targetFolder}/${widgetName}/lang/${langName}.json`, jsonData, { spaces: 2 });
      }
    });
  });
};

const parseLanguageFile = (filePath) => {
  const fileContent = fs.readFileSync(filePath).toString();
  const temp = fileContent.replace(/\/\/\s\S+/gm, '')
    .replace(/[\r\n\s]+/mg, '')
    .replace(/'/mg, '"')
    .replace(/,}/mg, '}')
    .match(/exportdefault(\{.+\});$/im);
  if (temp && temp.length > 1) {
    const jsonData = temp.pop().replace(/("?[a-zA-Z]+"?):/img, (text) => {
      if (text.includes('"')) return text;
      return `"${text.replace(/:/g, '')}":`;
    });
    return JSON.parse(jsonData);
  }
  return '';
};

const getComponents = () => {
  return Object.keys(packages.exposes).map((key) => key);
};

const getWidgetVersion = (widgetPath) => {
  const fileContent = fs.readFileSync(widgetPath).toString();
  simplifiedContent = fileContent.replace(/\/\/\s\S+/gm, '')
    .replace(/[\r\n\s'"]+/mg, '');
  const versionMatch = simplifiedContent.match(/version:(\d+\.\d+\.\d+)/im);
  if (versionMatch && versionMatch.length === 2) return versionMatch.pop();
  return '';
};

const getEntryContent = () => {
  const entryFile = './dist/remoteEntry.js';
  let fileContent = fs.readFileSync(entryFile).toString();

  /******/
  fileContent = fileContent.replace(/\/\*([*]+)\*\//g, '');
  fileContent = fileContent.replace(/\/\*!([*]+)!\*\\/g, '');
  fileContent = fileContent.replace(/!\*\*(.*)\*\*!/g, '');
  fileContent = fileContent.replace(/\\\*([*]+)\*\//g, '');
  fileContent = fileContent.replace(/\/\*(.*)\*\//g, '');

  // 删除双横杠注释
  fileContent = fileContent.replace(/\/\/ (.*)\r\n/g, '');
  fileContent = fileContent.replace(/\/\/ (.*)\r/g, '');
  fileContent = fileContent.replace(/\/\/ (.*)\n/g, '');

  // 删除换行和空格
  fileContent = fileContent.replace(/\r\n/g, '');
  fileContent = fileContent.replace(/\s+/g, ' ');

  return fileContent;
};


const mapJSFiles = () => {
  const fileContent = getEntryContent();
  const components = getComponents();
  console.log(components, 'components');
  components.forEach(key => {
    const name = packages.exposes[key].name;
    // // 创建文件目录
    fs.emptyDirSync(targetFolder + '/' + name);
    createDirectoryIfNotExist(targetFolder, [name]);
    createDirectoryIfNotExist(targetFolder, [name, 'js']);
    createDirectoryIfNotExist(targetFolder, [name, 'img']);
    createDirectoryIfNotExist(targetFolder, [name, 'css']);

    fs.copySync(fromFolder + '/js', targetFolder + '/' + name + '/js');
    if (isDirectory(fromFolder + '/img')) {
      fs.copySync(fromFolder + '/img', targetFolder + '/' + name + '/img');
    }
    if (isDirectory(fromFolder + '/css')) {
      fs.copySync(fromFolder + '/css', targetFolder + '/' + name + '/css');
    }

    const content = fileContent.replace(/\/\/#.+/g, '');
    fs.writeFileSync(targetFolder + '/' + name + '/index.js', content);
  });
  
};

// 打包
const mapCompress = () => {
  Object.keys(packages.exposes).forEach((key) => {
    const component = packages.exposes[key];
    const dir = targetFolder + '/' + component.name;
    const tar = dir + '.zip';
    compressing.zip.compressDir(dir, tar).then(() => {});
  });
};

// -------------文件操作相关-------------//

/**
 * 检查目标目录是否存在，不存在则创建
 *
 * @param {*} dst // 目标目录
 * @param {*} childFolder // 子目录数组
 */
function createDirectoryIfNotExist (dst, childFolder = []) {
  if (dst === '') {
    return;
  }
  if (isDirectory(dst)) {
    let targetDir = dst;
    childFolder.forEach((child) => {
      targetDir += '/' + child;
      if (!fs.existsSync(targetDir)) {
        fs.mkdirSync(targetDir);
      }
    });
    return;
  }
  const dstArray = dst.split('/');
  const parent = dstArray.slice(0, dstArray.length - 1).join('/');
  const child = dstArray.slice(dstArray.length - 1);
  childFolder.unshift(child);

  createDirectoryIfNotExist(parent, childFolder);
}

/**
 * 判断路径是否为目录
 * @param {string} dir
 */
function isDirectory (dir) {
  try {
    const stats = fs.statSync(dir);
    return stats.isDirectory();
  } catch (e) {
    return false;
  }
}

// 执行
(() => {
  mapJSFiles();
  genLangJson();
  // mapCompress();
})();
